package com.bkhc.product.repository;

import com.bkhc.product.entity.Brand;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Repository
public interface BrandRepository extends JpaRepository<Brand,String>, JpaSpecificationExecutor<Brand> {

    default Page<Brand> findAll(Brand brand, Pageable pageable){
        return findAll(new Specification<Brand>() {
            @Override
            public Predicate toPredicate(Root<Brand> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicate = new ArrayList<>();
                if(!StringUtils.isEmpty(brand.getBrandCode())){
                    predicate.add(criteriaBuilder.equal(root.get("brandCode").as(String.class), brand.getBrandCode()));
                }
                if(!StringUtils.isEmpty(brand.getBrandName())){
                    predicate.add(criteriaBuilder.like(root.get("brandName").as(String.class),"%"+ brand.getBrandName()+"%"));
                }
                Predicate[] pre = new Predicate[predicate.size()];

                return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
            }
        },pageable);


    }

    Brand findByBrandCode(String brandCode);

    void deleteByBrandCode(String brandCode);

    Brand findByBrandName(String brandName);

    @Query("select b from Brand b where not EXISTS(select pd.brandCode from PartnerBrand pd where pd.brandCode=b.brandCode)")
    List<Brand> findUnassigned();

    @Query("select b from Brand b where b.brandCode in (select bp.brandCode from BrandProduct bp where bp.productCode=?1)")
    List<Brand> getBrandByProduct(String productCode);
}
